//定义全局变量
var adminGrid;//表格
var dhxWins,addAdminWin,authorityWin; //窗口
var searchType=[['', '-- 请选择 --'],['1', '账号'], ['2', '姓名'],['3', '手机号']];
var oneAdminInfo; //一条管理员
var editStatus; //管理员状态
var dhxWinPwd, w1, pwdForm;
//页面布局
var pageObj = {type:"0100",height:[50,,45],paging:true,size:15}
var layoutContainer = create_layout(pageObj);
//初始化操作
$(function(){
	initGrid();
});
//初始化表格
function initGrid(){
	//获取表格对象
	adminGrid = layoutContainer.grid[0];
	//定义表格表头
	var columnsInfo=[{header:'id',id:'id',width:'*',hidden:true},
		{header:'账号',id:'userName',width:150 },
		{header:'来源',id:'source',width:130 ,hidden:true },
		{header:'密码',id:'password',width:130  ,hidden:true},
		{header:'密码加盐',id:'salt',width:130  ,hidden:true },
		{header:'邮箱',id:'email',width:150 },
		{header:'手机号码',id:'telephone',width:130},
		{header:'活动关联医院',id:'hosCode',width:130  ,hidden:true },
		{header:'姓名',id:'realName',width:130  },
		{header:'备注',id:'remark',width:130  ,hidden:true},
		{header:'状态',id:'status',width:130,type:'combo'},
		{header:'用户类型',id:'userType',width:130, type:'combo'},
		{header:'角色',id:'role_name',width:100},
		{header:'登入时间',id:'last_login_num',width:130  ,hidden:true},
		{header:'登入次数',id:'login_num',width:130  ,hidden:true},
		{header:'创建时间',id:'gmt_create',width:'*'},
		{header:'修改时间 ',id:'gmt_modify',width:130  ,hidden:true },
		{header:'添加人员',id:'operator',width:130 },
	];
	//创建表格
	dmjplugs.grid.createGrid({ sm:'ch',  skin:'dhx_skyblue', srcc:true,  columns:columnsInfo },adminGrid);
	adminGrid.setTotal(0);
	adminGrid.getColumnCombo(adminGrid.getColIndexById('status')).addOption(statusComboData);
	adminGrid.getColumnCombo(adminGrid.getColIndexById('userType')).addOption(roleTypeComboData);
	adminGrid.enableEditEvents(false,false,false);
	adminGrid.setColSorting("str,int,str,str,str,str,str,int,str,str,str,str,str,str,str,int,str,str,str");
	//注册分页事件
	adminGrid.attachEvent("loadPagingData", function(first, limit){
		findPageGrid(first, limit);
	});
	//注册行点击事件
	adminGrid.attachEvent("onRowSelect",doOnRowSelected);
	adminGrid.attachEvent("onRowDblClicked",function () {
		doEdit('edit');
	});
	//隐藏掉复选框
	adminGrid.setColumnHidden(0,true);

	//获取表格数据
	findPageGrid();
}
//根据选择条件,获取表格数据	
function findPageGrid(first,limit){
	//初始化表格为空表
	if (!limit) {
		first = 0;
		limit = adminGrid.getPageRowLimit();
		adminGrid.clearAll();
		adminGrid.setTotal(0);
	}
	//分页组件数据
	var postData="pageNo="+parseInt(first/limit+1)+"&pageSize="+limit+"&pageCount="+adminGrid.getPageTotal()+"&hosType=2" ;
	//查询条件
	if (typeof (search_Form) == 'object') {
		var formData = search_Form.getFormData();//获取查询表单数据
		var searchKey = search_Form.getInput("searchKey").value;
		var searchType=formData.searchType;
		var userType=formData.userType;
		var roleId=formData.roleId;
		var status=formData.status;
		// var roleName = search_Form.getInput("roleName").value;
		//var searchKey=formData.searchKey;
		if(searchKey&&searchKey.length>0) postData+=(searchType==1?"&userName=":searchType==2?"&realName=":searchType==3?"&telephone=":"&bb=")+searchKey;
		if(userType&&userType.length>0){
			postData+="&userType="+userType;
		}
		if(roleId&&roleId.length>0){
			postData+="&roleId="+roleId;
		}
		if(status&&status.length>0){
			postData+="&status="+status;
		}
		/*if(roleName&&roleName.length>0){
			postData+="&roleName="+roleName;
		}*/
		var startTimeCalendar = search_Form.getInput('startTime');
		var endTimeCalendar = search_Form.getInput('endTime');
		if(startTimeCalendar&&startTimeCalendar.value&&startTimeCalendar.value.length>0){
			postData+="&begintimeStr="+startTimeCalendar.value;
		}
		if(endTimeCalendar&&endTimeCalendar.value&&endTimeCalendar.value.length>0){
			postData+="&endtimeStr="+endTimeCalendar.value;
		}
	}
	$.ajax({
		url: basePath+'managerUser/findPageGrid',
		type: 'post',
		dataType: 'json', //返回的数据类型
		data:encodeURI(postData),
		success: function (data) {
			if(data&&data.rowCount>0){
				adminGrid.parse(data.gridr, "json");
				adminGrid.setTotal(data.rowCount);
				adminGrid.uncheckAll();
			}
		}
	});
}
//------------------------------------------------顶部操作区----------------------------------------------------------------------
// 顶部查询按钮	注册点击事件
function doOnButtFormInit() {
	if (typeof (butt_Form) == 'object') {
		butt_Form.attachEvent("onButtonClick",function(name,command) {
			if (command == 'add')//新增
				doAdd('add');
			else if (command == 'edit')//编辑
				doEdit('edit');
			else if (command == 'freeze')//冻结账号
				doFreeze();
			else if (command == 'refresh')//刷新
				doRefresh();
			else if (command == 'delete')//删除用户
				doDelete();
			else if (command == 'authority')//数据授权
				doAuthority();
		});
	}
}
//顶部查询框初始化	
function doOnSearchFormInit(){
	if (typeof(search_Form) == "object"){
		moduleSearchInit();
		search_Form.attachEvent("onButtonClick", function(name, command) {
			if (command == 'search')
				doRefresh();
			else if(command == 'reset')
				doReset();
		});

		var startTimeCalendar = search_Form.getCalendar('startTime');
		startTimeCalendar.setDateFormat("%Y-%m-%d %H:%i:%s");
		startTimeCalendar.showTime();
		var endTimeCalendar = search_Form.getCalendar('endTime');
		endTimeCalendar.setDateFormat("%Y-%m-%d %H:%i:%s");
		endTimeCalendar.showTime();
		//限制日期输入
		$("input[name='startTime']").keyup(function(){
			var tmptxt=$(this).val();
			if(validateDate(tmptxt)){
				$(this).val(tmptxt.replace(/[^0-9- :]/g,''));
			}

		}).change(function(){
			var tmptxt=$(this).val();
			if(validateDate(tmptxt)){
				tmptxt=tmptxt.replace(/[^0-9- :]/g,'');
			}
			$(this).val(tmptxt);
			if(!checkDateStr('yyyy-MM-dd hh:mm:ss',tmptxt)){
				$func.alert("筛选条件提交时间起始录入不规范！");
				dateFlag=false;
			}else{
				dateFlag=true;
			}
		}).css("ime-mode", "disabled").attr('placeholder','yyyy-MM-dd hh:mm:ss').attr("maxlength",19);
		$("input[name='endTime']").keyup(function(){
			var tmptxt=$(this).val();
			if(validateDate(tmptxt)){
				$(this).val(tmptxt.replace(/[^0-9- :]/g,''));
			}
		}).change(function(){
			var tmptxt=$(this).val();
			if(validateDate(tmptxt)){
				tmptxt=tmptxt.replace(/[^0-9- :]/g,'');
			}
			$(this).val(tmptxt);
			if(!checkDateStr('yyyy-MM-dd hh:mm:ss',tmptxt)){
				$func.alert("筛选条件提交时间截止录入不规范！");
				dateFlag1=false;
			}else{
				dateFlag1=true;
			}
		}).css("ime-mode", "disabled").attr('placeholder','yyyy-MM-dd hh:mm:ss').attr("maxlength",19);

		var searchType_combo=search_Form.getCombo('searchType');
		searchType_combo.addOption(searchType);
		searchType_combo.setComboValue('2');
		searchType_combo.readonly(true);
		search_Form.setItemFocus("searchKey");

		var userType_combo=search_Form.getCombo('userType');
		userType_combo.addOption(roleTypeComboData);
		userType_combo.setComboValue('');
		userType_combo.readonly(true);

		var roleId_combo=search_Form.getCombo('roleId');
		roleId_combo.addOption(roleComboData);
		roleId_combo.setComboValue('');
		roleId_combo.readonly(true);

		var status_combo=search_Form.getCombo('status');
		status_combo.addOption(statusComboData);
		status_combo.deleteOption('delete');
		status_combo.setComboValue('');
		status_combo.readonly(true);

		$('input.dhxlist_txt_textarea').keypress(function(event){
			if(event.keyCode == 13){ //绑定回车
				findPageGrid();
			}
		});
	}
}
//刷新按钮
function doRefresh(){
	findPageGrid();
}
function doEdit(type){
	if(type!='edit')return;
	var admins =  getCheckedRowsByGrid(adminGrid, adminGrid.getColIndexById('select'));
	if (admins == null||admins.length > 1) {
		$func.alert("请选择一行再操作[编辑]", "red");
		return;
	}
	oneAdminInfo=admins[0];
	if(!oneAdminInfo||!oneAdminInfo.id){
		$func.alert("所选择行数据有问题,请选择其他行或者刷新页面重试", "red");
		return;
	}
	if(type == 'edit'){
		checkParam(admins[0].id);
	}
	openWindow(type,oneAdminInfo.id)
}

//--------------------------------------------------事件方法--------------------------------------------------------------------------
function doAdd(type){
	if(type!='add')return;
	openWindow(type)
}
function openWindow(type,id){
	if(!id) id=-1;
	if(!dhxWins)dhxWins=new dhtmlXWindows();
	dhxWins.setImagePath(basePath + "js/dhtmlx/dhtmlxWindows/codebase/imgs/");
	if(type=='add')addAdminWin=dhxWins.createWindow("addAdminWin", 10, 10, 490, 500);
	if(type=='edit')addAdminWin=dhxWins.createWindow("addAdminWin", 10, 10, 490, 500);
	addAdminWin.center();
	addAdminWin.setModal(true);
	addAdminWin.bringToTop();
	addAdminWin.setText("<span style=\"font-size:14px;\">"+(type=="add"?"新增账号":"编辑账号")+"</span>");
	addAdminWin.denyResize();
	addAdminWin.button("minmax1").hide();
	addAdminWin.button("park").hide();
	addAdminWin.attachURL(basePath+"managerUser/editManagerUserWin?type="+type+"&id="+id);
}

function unloadPwdWin() { //放到body里面
	if (dhxWinPwd != null && dhxWinPwd.unload != null) {
		dhxWinPwd.unload();
		dhxWinPwd = w1 = pwdForm = null;
	}
}
//管理员账户状态 有效和冻结
function doFreeze(){
	var admins = getCheckedRowsByGrid(adminGrid, adminGrid.getColIndexById('select'));
	if (admins == null||admins.length > 1) {
		$func.alert("请选择一行再操作", "red");
		return;
	}
	var postData="id="+admins[0].id;
	var confirmArr = "是否冻结该账户【"+admins[0].userName+"】？ <br/><font color='#ff66;'>冻结后该账户将无法登录！</font>";
	if(editStatus=="enabled"){
		postData+="&status=freeze";
	}else if(editStatus=="freeze"){
		confirmArr = "是否解除冻结账户【"+admins[0].userName+"】？ <br/><font color='#ff66;'>解除冻结后该账户恢复可登录状态！</font>";
		postData+="&status=enabled";
	}else if(editStatus=="delete"){
		$func.alert('删除状态不能更改！', 'red');
		return ;
	}
	checkParam(admins[0].id);
	$func.confirm({
		content : confirmArr,
		ok : function() {
			$.ajax({
				url: basePath+'managerUser/editManagerUser',
				type: 'post',
				dataType: 'json',
				data:postData,
				success: function (back, textStatus, jqXHR) {
					if(!back||!back.result){
						$func.alert("账户 ["+admins[0].userName+"] "+(editStatus=='enabled'?"冻结":editStatus=='disabled'?"解除":"恢复")+"失败！","red");
						return;
					}
					$func.alert("账户 ["+admins[0].userName+"] "+(editStatus=='enabled'?"冻结":editStatus=='disabled'?"解除":"恢复")+"成功！","green");
					doRefresh();
				},
				error:function (xhr, textStatus, errorThrown) {
					$func.alert("操作失败", "red");
				}
			});
		}
	});
}

function doDelete(){
	var admins = getCheckedRowsByGrid(adminGrid, adminGrid.getColIndexById('select'));
	if (admins == null||admins.length==0) {
		$func.alert("至少选择一行再操作[删除]", "red");
		return;
	}
	if (admins.length>1) {
		$func.alert("不支持多行删除，请选择一行再操作[删除]", "red");
		return;
	}
	if(admins[0].status=="delete"){
		$func.alert("目前已是删除状态，无需再作[删除]", "red");
		return;
	}
	checkParam(admins[0].id);
	var adminids=[];
	$.each(admins,function(k,v){
		adminids.push(v.id);
	});
	var confirmArr = "是否删除账户【"+admins[0].userName+"】</font>？ ";
	var postData="id="+adminids;
	$func.confirm({
		content : confirmArr,
		ok : function() {
			$.ajax({
				url: basePath+ 'managerUser/delManagerUser',
				type: 'post',
				dataType: 'json',
				data:postData,
				success: function (back) {
					if(!back||!back.result){
						$func.alert("删除失败！","red");
						return;
					}
					$func.alert("删除成功，本次操作共计删除"+admins.length+"个账户","green");
					doRefresh();
				}
			});
		}
	});
}
//管理员账户状态只有两种有效和冻结
function doOnRowSelected(rowID, celInd){
	editStatus	= adminGrid.cells(rowID, adminGrid.getColIndexById('status')).getValue();
	$("#freeze").html("<span>"+(editStatus=='enabled'?"冻结":editStatus=='disabled'?"解冻":"恢复")+"</span>");
}
function doReset(){
	search_Form.setItemValue("searchKey","");
	//单个重置
	var tcombo=search_Form.getCombo('searchType');
	tcombo.setComboValue('');
	tcombo.readonly(true);
	// search_Form.setItemValue("roleName","");
	var status=search_Form.getCombo('status');
	status.setComboValue('');
	status.readonly(true);
	var userType=search_Form.getCombo('userType');
	userType.setComboValue('');
	userType.readonly(true);
	var roleId=search_Form.getCombo('roleId');
	roleId.setComboValue('');
	roleId.readonly(true);
	var startTimeCalendar = search_Form.getInput('startTime');
	startTimeCalendar.value = "";
	var endTimeCalendar = search_Form.getInput('endTime');
	endTimeCalendar.value = "";
	//批量重置
	search_Form.setFormData({
		realName:'',
		email:'',
		telephone:''
	});
}

//数据授权绑定管理功能
function doAuthority() {
	var admins = getCheckedRowsByGrid(adminGrid, adminGrid.getColIndexById('select'));
	if (admins == null||admins.length==0) {
		$func.alert("至少选择一行再操作[数据授权]", "red");
		return;
	}
	oneAdminInfo = admins[0];
	if (admins.length>1) {
		$func.alert("不支持批量授权，请选择一行再操作[数据授权]", "red");
		return;
	}
	checkParam(admins[0].id);

	if(!dhxWins)dhxWins=new dhtmlXWindows();
	dhxWins.setImagePath(basePath + "js/dhtmlx/dhtmlxWindows/codebase/imgs/");
	authorityWin=dhxWins.createWindow("authorityWin", 10, 10, 520, 500);
	authorityWin.center();
	authorityWin.setModal(true);
	authorityWin.bringToTop();
	authorityWin.setText("<span style=\"font-size:14px;\">"+"数据授权"+"</span>");
	authorityWin.denyResize();
	authorityWin.button("minmax1").hide();
	authorityWin.button("park").hide();
	authorityWin.attachURL(basePath+"managerUser/gotoAuthorityWin?id="+admins[0].id);
}
